using IuliiaBot.Application.Interfaces;
using Telegram.Bot;
using Telegram.Bot.Exceptions;
using Telegram.Bot.Polling;
using Telegram.Bot.Types;
using static System.Console;

namespace IuliiaBot.Telegram;

public class IuliiaTelegramService
{
    private readonly ITelegramBotClient _botClient;
    private readonly ReceiverOptions _receiverOptions;
    private readonly ICommandFactory<Update> _commandFactory;

    public async Task Run()
    {
        _botClient.StartReceiving(UpdateHandler, ErrorHandler, _receiverOptions);

        var me = await _botClient.GetMeAsync();
        WriteLine($"{me.FirstName} is running!");

        await Task.Delay(-1);   // ожидание сообщений
    }

    private Task ErrorHandler(ITelegramBotClient client, Exception exception, CancellationToken _)
    {
        var ErrorMessage = exception switch
        {
            ApiRequestException apiRequestException
                => $"Telegram API Error:\n[{apiRequestException.ErrorCode}]\n{apiRequestException.Message}",
            _ => exception.ToString()
        };

        WriteLine(ErrorMessage);

        return Task.CompletedTask;
    }

    private async Task UpdateHandler(ITelegramBotClient client, Update update, CancellationToken _)
    {
        var sander = new TelegramSander(_botClient, update);
        var command = _commandFactory.GetCommand(update, sander);
        await command.RunCommandAsync();
    }

    public IuliiaTelegramService(ITelegramBotClient botClient, ReceiverOptions receiverOptions, ICommandFactory<Update> commandFactory)
    {
        _botClient = botClient;
        _receiverOptions = receiverOptions;
        _commandFactory = commandFactory;
    }
}
